<?php

declare(strict_types=1);

namespace app\version\controller;

use app\admin\BaseAdminController;
use think\facade\View;
use app\version\model\Version;
use think\facade\Config;
use app\system\model\LogOperate as Log;

class Index extends BaseAdminController
{
    /**
     * APP 版本管理页面
     */
    public function index()
    {
        View::assign('title', '版本列表/版本管理');
        return View::fetch();
    }

    /**
     * 新增版本信息
     */
    public function save()
    {
        if ($this->envMode == 'demo'){
            return $this->isDemo();
        }
        $version = input('version');
        $address = input('address');
        $info = input('info');
        $size = 0;
        $pre = Config::get('filesystem.disks.public.url');
        $path = Config::get('filesystem.disks.public.root');
        $path = str_replace($pre, '', $path);
        $file = $path . $address;
        $size = filesize($file);
        $obj = new Version;
        $obj->save([
            'admin_id' => UID,
            'version' => $version,
            'url' => $address,
            'info' => $info,
            'size' => $size,
        ]);
        Log::add('新增App版本', [
            'ID' => $obj->id,
            '版本' => $version,
            '地址' => $address,
            '说明' => $info,
        ]);
        return json(['msg' => '']);
    }

    /**
     * 读取 APP 版本信息列表
     */
    public function data()
    {
        $offset = input('offset/d');
        $limit = input('limit/d');
        $obj = new Version();
        $count = $obj->count();
        $obj = $obj->with([
            'user' => function ($query) {
                $query->field('id, nickname');
            }
        ]);
        $list = $obj->order('id', 'desc')->limit($offset, $limit)->select();
        $new = [];
        foreach ($list as $value) {
            $value['size'] = formatBytes($value['size']);
            $new[] = $value;
        }
        return json([
            'total' => $count,
            'rows' => $new,
        ]);
    }
}
